package com.yuyou.fn.controller;

import com.yuyou.fn.common.lang.Tuple2;
import com.yuyou.fn.common.util.Principals;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.ISysDataPermissionService;
import com.yuyou.fn.platform.service.ISysUserService;
import com.yuyou.fn.platform.vo.AccessTokenVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by wens on 2017/2/22.
 */
public class ApiBaseController {

    private static class SmartCustomDateEditor extends PropertyEditorSupport{

        private final static List<Tuple2<Pattern,String>> suppertPatterns = Arrays.asList(
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}") , "yyyy-MM-dd"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}") , "yyyy-MM-dd HH"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}") , "yyyy-MM-dd HH:mm"),
                Tuple2.of(Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}") , "yyyy-MM-dd HH:mm:ss")
                );


        private SimpleDateFormat simpleDateFormat ;


        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if(!StringUtils.hasText(text)) {
                this.setValue((Object)null);
            }else {
                for(Tuple2<Pattern,String> patternStringTuple : suppertPatterns ){

                    if(patternStringTuple.getFirst().matcher(text).matches()){
                        simpleDateFormat = new SimpleDateFormat(patternStringTuple.getSecond());
                        simpleDateFormat.setLenient(false);
                        break;
                    }
                }
                if( simpleDateFormat == null ){
                    throw new IllegalArgumentException("Could not parse date: " + text );
                }

                try {
                    this.setValue(this.simpleDateFormat.parse(text));
                } catch (ParseException var3) {
                    throw new IllegalArgumentException("Could not parse date: " + var3.getMessage(), var3);
                }
            }




        }

        @Override
        public String getAsText() {
            Date value = (Date)this.getValue();
            return value != null ? this.simpleDateFormat.format(value) : "";
        }
    }


    @Resource
    protected ISysUserService sysUserService ;

    @Resource
    protected ITeacherService teacherService;

    @Resource
    protected ISysDataPermissionService sysDataPermissionService ;


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new SmartCustomDateEditor() );
    }

    protected Long getUserId(HttpServletRequest request) {
        AccessTokenVo accessToken = (AccessTokenVo)request.getAttribute("accessToken");
        Assert.notNull(accessToken);
        return accessToken.getUserId();
    }

    protected SysUser getUser(HttpServletRequest request) {
        return sysUserService.findByUserIdFromCache(getUserId(request));
    }

    protected Principals.Principal getCurrentSysPrincipal(){
        Principals.Principal principal = Principals.get();
        principal.name = sysUserService.findByUserIdFromCache(principal.id).getRealName();
        return principal;
    }

    protected DataPermission getDataPermission(HttpServletRequest request) {
        DataPermission dataPermission = sysDataPermissionService.findDataPermissionForUser(getUserId(request));
        return dataPermission ;
    }


    protected Long getTeacherId(HttpServletRequest request) {
        AccessTokenVo accessToken = (AccessTokenVo)request.getAttribute("accessToken");
        Assert.notNull(accessToken);
        return accessToken.getUserId();
    }

    protected Teacher getTeacher(HttpServletRequest request) {
        return teacherService.findById(getTeacherId(request));
    }

}
